package test.demo.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author Hinsteny
 * @date 2016/5/25
 * @copyright: 2016 All rights reserved.
 */
public class NioClient {

	private String address = "127.0.0.1";
	private int port = 7777;

	private Charset charset = Charset.forName("UTF-8");
	private Selector selector = null;
	private SocketChannel sc = null;

	public NioClient(String address, int port) throws IOException {
		this.address = address;
		this.port = port;
	}

	public void work() throws IOException {
		selector = Selector.open();
        //连接远程主机的IP和端口
        sc = SocketChannel.open(new InetSocketAddress(address, port));
        sc.configureBlocking(false);
        sc.register(selector, SelectionKey.OP_READ);
        //开辟一个新线程来读取从服务器端的数据
        new Thread(new ClientThread()).start();
        //在主线程中 从键盘读取数据输入到服务器端
        Scanner scan = new Scanner(System.in);
        String line = "";
        while(scan.hasNextLine()){
            line = scan.nextLine();
            if("".equals(line)) continue; //不允许发空消息
            if("exit".equals(line)) break;
            else line = NioServer.BROAD_CAST_FLAG + line;
            sc.write(charset.encode(line));//sc既能写也能读，这边是写
        }
        scan.close();
	}

	private class ClientThread implements Runnable {
		
		@SuppressWarnings("rawtypes")
		public void run() {
			try {
				while (true) {
					int readyChannels = selector.select();
					if (readyChannels == 0)
						continue;
					Set selectedKeys = selector.selectedKeys(); // 可以通过这个方法，知道可用通道的集合
					Iterator keyIterator = selectedKeys.iterator();
					while (keyIterator.hasNext()) {
						SelectionKey sk = (SelectionKey) keyIterator.next();
						keyIterator.remove();
						dealWithSelectionKey(sk);
					}
				}
			} catch (IOException io) {
			}
		}

		private void dealWithSelectionKey(SelectionKey sk) throws IOException {
			if (sk.isReadable()) {
				// 使用 NIO 读取 Channel中的数据，这个和全局变量sc是一样的，因为只注册了一个SocketChannel
				// sc既能写也能读，这边是读
				SocketChannel sc = (SocketChannel) sk.channel();

				ByteBuffer buff = ByteBuffer.allocate(1024);
				String content = "";
				while (sc.read(buff) > 0) {
					buff.flip();
					content += charset.decode(buff);
				}
				System.out.println(content);
				sk.interestOps(SelectionKey.OP_READ);
			}
		}
	}

	public static void main(String[] args) throws IOException {
		// 种10个线程发起Socket客户端连接请求
		for (int i = 0; i < 1; i++) {
			new NioClient("127.0.0.1", 7777).work();
		}
	}
}
